package com.zlt.utils;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.sql.DataSource;

public class JdbcTemplateUtil {

    private static DataSource dataSource;

    private static JdbcTemplate jdbcTemplate;

    private static ThreadLocal<DataSourceTransactionManager> tcms = new ThreadLocal<>();

    private static ThreadLocal<TransactionStatus> tcs = new ThreadLocal<>();

    static {
        jdbcTemplate = new JdbcTemplate();
        dataSource = DataSourceUtil.getDataSource();
        jdbcTemplate.setDataSource(dataSource);
    }

    /**
     * 获取jdbctemplate对象
     * @return
     */
    public static JdbcTemplate getJdbcTemplate(){
        return jdbcTemplate;
    }

    //开启事务
    public static void beginTransaction(int propagation){
        DefaultTransactionDefinition tc = new DefaultTransactionDefinition();
        tc.setPropagationBehavior(propagation);
        DataSourceTransactionManager transactionManager = getTransactionManager();
        tcms.set(transactionManager);
        TransactionStatus transaction = transactionManager.getTransaction(tc);
        tcs.set(transaction);
    }

    //提交事务
    public static void commit(){
        DataSourceTransactionManager dataSourceTransactionManager = tcms.get();
        if(dataSourceTransactionManager != null){
            TransactionStatus transactionStatus = tcs.get();
            if(transactionStatus != null){
                dataSourceTransactionManager.commit(transactionStatus);
            }
        }
    }

    //回滚事务
    public static void rollback(){
        DataSourceTransactionManager dataSourceTransactionManager = tcms.get();
        if(dataSourceTransactionManager != null){
            TransactionStatus transactionStatus = tcs.get();
            if(transactionStatus != null){
                dataSourceTransactionManager.rollback(transactionStatus);
            }
        }
    }

    private static DataSourceTransactionManager getTransactionManager(){
        return new DataSourceTransactionManager(dataSource);
    }
}
